package com.sx.shopping.service.goods;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sx.common.util.NumberUtil;
import com.sx.common.util.json.JackJsonUtil;
import com.sx.manage.exception.MAjaxErrorRollbackException;
import com.sx.manage.service.company.IMBaseCompanyService;
import com.sx.manage.service.consumer.IMBaseSystemConsumerInfoService;
import com.sx.manage.service.consumer.IMSystemConsumerInfoService;
import com.sx.manage.service.goods.IMGoodsInfoService;
import com.sx.manage.service.goods_relation.IMServeObjectInfoService;
import com.sx.model.constants.MDataStatusType;
import com.sx.model.constants.MSystemConstants;
import com.sx.model.manage.mybatis.form.consumer.MCompanyForm;
import com.sx.model.manage.mybatis.vo.bank.MDropDownVO;
import com.sx.model.manage.mybatis.vo.company.MCompanyVO;
import com.sx.model.manage.mybatis.vo.consumer.MSystemConsumerInfoVO;
import com.sx.model.manage.mybatis.vo.consumer.login.MConsumerLoginVO;
import com.sx.model.manage.mybatis.vo.result.ResultBooleanVO;
import com.sx.model.manage.mybatis.vo.result.ResultDropDownListVO;
import com.sx.model.manage.mybatis.vo.result.ResultListVO;
import com.sx.model.manage.mybatis.vo.result.ResultObjectVO;
import com.sx.model.manage.mybatis.vo.result.ResultUploadVO;
import com.sx.model.shopping.mybatis.constants.MShoppingConstants;
import com.sx.model.shopping.mybatis.constants.type.GoodsDateType;
import com.sx.model.shopping.mybatis.form.goods.MGoodsInfoForm;
import com.sx.model.shopping.mybatis.form.goods_relation.MServeObjectInfoForm;
import com.sx.model.shopping.mybatis.vo.goods.MGoodsInfoVO;
import com.sx.model.shopping.mybatis.vo.goods_relation.MServeObjectInfoVO;

/**
 * 商品web程序中service实现类
 * 
 * @author lenovo
 *
 */
@Service("goodsInfoWebService")
@Transactional(propagation = Propagation.REQUIRED)
public class MGoodsInfoWebService {
	/*** 日志 */
	private Logger log = LoggerFactory.getLogger(this.getClass());
	@Resource(name = "goodsInfoServiceImpl")
	private IMGoodsInfoService goodsInfoServiceImpl;
	@Resource(name = "serveobjectinfoserviceimpl")
	private IMServeObjectInfoService serveobjectinfoserviceimpl;

	@Resource(name = "mBaseCompanyServiceImpl")
	private IMBaseCompanyService mBaseCompanyServiceImpl;

	// 系统用户service
	@Resource(name = "systemConsumerInfoServiceImpl")
	private IMSystemConsumerInfoService systemConsumerInfoServiceImpl;

	// 系统用户service
	@Resource(name = "mBaseSystemConsumerInfoServiceImpl")
	private IMBaseSystemConsumerInfoService mBaseSystemConsumerInfoServiceImpl;

	/** 1增加数据 */
	public ResultBooleanVO saveAndIssue(MGoodsInfoForm form, MConsumerLoginVO loginConsumer) {
		log.debug("首选增加商品(保存并发布)：" + JackJsonUtil.objToJson(form));
		if (null == form) {
			return new ResultBooleanVO("m.parameter.is.null");
		}
		form.setState(MSystemConstants.ONLINE);
		return save(form, loginConsumer);
	}

	/** 1增加数据 */
	public ResultBooleanVO save(MGoodsInfoForm form, MConsumerLoginVO loginConsumer) {
		log.debug("首选增加商品（保存）：" + JackJsonUtil.objToJson(form));

		ResultBooleanVO result = this.validateForm(form);
		if (!result.isSuccess()) {
			return result;
		}
		if (null == form.getState()) {
			form.setState(MSystemConstants.OFFLINE);
		}
		form.setCreate_time(new Date());
		form.setConsumer_id(loginConsumer.getConsumer_id());

		ResultObjectVO<MGoodsInfoForm> formResult = goodsInfoServiceImpl.save(form, loginConsumer);
		if (!formResult.isSuccess()) {
			log.debug("添加商品出错返回：" + formResult.getMsg());
			return new ResultBooleanVO(false, null, formResult.getMsg());
		}
		form = formResult.getObjVo();
		if (null != form.getBusiness_ids() || null != form.getId()) {
			log.debug("发布对象不为空开始增加关系business_ids=" + NumberUtil.arrayToStr(form.getBusiness_ids()));
			result = saveGoodsRelation(form, loginConsumer);
			if (!result.isSuccess()) {
				throw new MAjaxErrorRollbackException(result.getMsg());// 返回到配置文件中定义的路径
			}
		}
		log.debug("添加商品完成");
		return result;
	}

	private ResultBooleanVO validateForm(MGoodsInfoForm form) {
		// 查询数据是否存在 状态如何
		if (null == form.getData_type()) {
			log.debug("发布类型为空");
			return new ResultBooleanVO(false, null, "商品发布状态为空！");
		}
		if (null != form.getId()) {
			ResultObjectVO<MGoodsInfoVO> vo = goodsInfoServiceImpl.queryById(form.getId());
			MGoodsInfoVO mvo = vo.getObjVo();
			if (null != mvo) {
				if (mvo.getState().equals(MSystemConstants.ONLINE)) {
					log.error("请将商品下架，再商品信息！");
					return new ResultBooleanVO(false, null, "请将商品下架，再修改商品信息！");
				}
			}
		}
		Long[] business_ids = form.getBusiness_ids();
		if (null != business_ids && business_ids.length > 0) {
			for (Long business_id : business_ids) {
				if (null != business_id && business_id.equals(form.getChannel_id())) {
					log.error("收款账户不能出现在发布对象内！" + form.getChannel_id());
					return new ResultBooleanVO(false, null, "收款账户不能出现在发布对象内！");
				}
			}
		}
		return new ResultBooleanVO();
	}

	/** 增加商品的发布对象 **/
	public ResultBooleanVO saveGoodsRelation(MGoodsInfoForm form, MConsumerLoginVO loginConsumer) {
		log.debug("开始增加发布对象");
		ResultBooleanVO result = null;
		if (null != form && null != form.getId()) {
			log.debug("根据service_id删除原有的关系");
			result = this.serveobjectinfoserviceimpl.deleteByServiceId(form.getId(), loginConsumer);
			if (!result.isSuccess()) {
				log.debug("根据service_id删除原有的关系时出错" + result.getMsg());
				return result;
			}
		}
		Long[] business_ids = form.getBusiness_ids();
		if (null == business_ids || business_ids.length == 0) {
			return new ResultBooleanVO();
		}

		List<MServeObjectInfoForm> formList = new ArrayList<>(business_ids.length);
		log.debug("生产发布对象数据集合");
		MServeObjectInfoForm objInfoForm = null;
		for (Long business_id : business_ids) {
			if (null != business_id) {
				objInfoForm = new MServeObjectInfoForm();
				objInfoForm.setCompany_id(business_id);
				objInfoForm.setData_status(MDataStatusType.DATA_AVAILABLE);
				objInfoForm.setService_id(form.getId());
				objInfoForm.setCreate_time(new Date());

				formList.add(objInfoForm);
			}
		}
		log.debug("开始批量新增商品发布对象数据");
		result = this.serveobjectinfoserviceimpl.saveBatch(formList, loginConsumer);
		return result;
	}

	/** 4根据id查询数据 */
	public ResultObjectVO<MGoodsInfoVO> queryById(Long id) {

		ResultObjectVO<MGoodsInfoVO> result = this.goodsInfoServiceImpl.queryById(id);
		log.debug("查询发布对象，操作人等数据");
		this.searchConsumerAndBusiness(result.getObjVo(), true);

		return result;
	}

	/** 5查询分页 */
	public ResultListVO<MGoodsInfoVO> queryPage(MGoodsInfoForm form) {

		List<GoodsDateType> dataTypeList = new ArrayList<>();
		dataTypeList.add(GoodsDateType.DATA_COMMING_SELF_SUPPORT);
		dataTypeList.add(GoodsDateType.DATA_TAX_CARE_FREE);
		form.setData_types(dataTypeList);
		ResultListVO<MGoodsInfoVO> result = this.goodsInfoServiceImpl.queryPage(form);
		log.debug("查询发布对象，操作人等数据");
		this.searchConsumerAndBusiness(result.getData(), false);
		return result;
	}

	/** 6 商品上架 */
	public ResultBooleanVO onLine(Long[] ids, MConsumerLoginVO loginConsumer) {
		return this.goodsInfoServiceImpl.editStatus(MShoppingConstants.GOODS_ON_LINE, ids, loginConsumer);
	}

	/** 6.1 商品下架 */
	public ResultBooleanVO offLine(Long[] ids, MConsumerLoginVO loginConsumer) {
		return this.goodsInfoServiceImpl.editStatus(MShoppingConstants.GOODS_OFF_LINE, ids, loginConsumer);
	}

	/** 7 根据or条件获取唯一数据 */
	public ResultObjectVO<MGoodsInfoVO> queryUniqueByOr(MGoodsInfoForm form) {
		return this.goodsInfoServiceImpl.queryUniqueByOr(form);
	}

	/** 8 根据 or 条件获取数据集合 */
	public ResultListVO<MGoodsInfoVO> queryListByOr(MGoodsInfoForm form) {
		return this.goodsInfoServiceImpl.queryListByOr(form);
	}

	/** 8.1 获取数据集合 */
	public ResultListVO<MGoodsInfoVO> queryList(MGoodsInfoForm form) {
		return this.goodsInfoServiceImpl.queryList(form);
	}

	/** 9 更新商品价格 */
	public ResultBooleanVO updateGoodPrice(BigDecimal price, Long id, MConsumerLoginVO loginConsumer) {
		return this.goodsInfoServiceImpl.updateGoodPrice(price, id, loginConsumer);
	}

	/** 10 更新商品图片信息 localimage */
	public ResultBooleanVO updateGoodLocalimage(String local_image, Long id, MConsumerLoginVO loginConsumer) {
		return this.goodsInfoServiceImpl.updateGoodLocalimage(local_image, id, loginConsumer);
	}

	/*** 11 图片上传 流程 */
	@RequestMapping(value = "/upload")
	@ResponseBody
	public ResultUploadVO upload(@RequestParam(value = "files", required = false) MultipartFile file, HttpServletRequest request, MConsumerLoginVO loginConsumer) {
		String paths = null;
		String path = request.getSession().getServletContext().getRealPath("upload");
		String fileName = file.getOriginalFilename();
		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
//		try {
//			file.transferTo(targetFile);
//			paths = OSSUtils.uploadFile(targetFile, MSystemConstants.SYS_UPLOAD_URL_);
//			targetFile.delete();
//			if (null == paths) {
//				return new ResultUploadVO("sj.m.common.upload.error");
//			}
//			log.info("上传文件成功，路径 :" + paths);
//		} catch (IllegalStateException e1) {
//			e1.printStackTrace();
//		} catch (IOException e1) {
//			e1.printStackTrace();
//		} catch (OSSException e) {
//			e.printStackTrace();
//		} catch (ClientException e) {
//			e.printStackTrace();
//		}
		ResultUploadVO result = new ResultUploadVO();
		result.setSuccess(true);
		result.setMsgcode("sj.m.common.upload.success");
		result.setPath(paths);
		return result;
	}

	/** 12 取消 ***/
	public ResultBooleanVO cancel(String sku_id, MConsumerLoginVO loginConsumer) {
		if (StringUtils.isBlank(sku_id)) {
			return new ResultBooleanVO("m.parameter.is.null");
		}
		return new ResultBooleanVO();
	}

	/** 商品集合查询发布对象等数据 **/
	public void searchConsumerAndBusiness(List<MGoodsInfoVO> voList, Boolean searchChannels) {
		if (null != voList && !voList.isEmpty()) {
			for (MGoodsInfoVO vo : voList) {
				searchConsumerAndBusiness(vo, searchChannels);
			}
		}
	}

	/** 单个商品查询发布对象等数据 **/
	public void searchConsumerAndBusiness(MGoodsInfoVO vo_, Boolean searchChannels) {
		if (null != vo_) {
			// 查询操作人
			if (null != vo_.getConsumer_id()) {
				ResultObjectVO<MSystemConsumerInfoVO> result = this.mBaseSystemConsumerInfoServiceImpl.queryById(vo_.getConsumer_id());
				if (null != result && null != result.getObjVo()) {
					vo_.setConsumer_name(result.getObjVo().getConsumer_name());
				}
			}
			if (null != vo_.getChannel_id()) {
				MCompanyForm form = new MCompanyForm();
				form.setId(vo_.getChannel_id());
				ResultObjectVO<MCompanyVO> result = this.mBaseCompanyServiceImpl.search_byIds(form);
				if (null != result && null != result.getObjVo()) {
					vo_.setChannel_name(result.getObjVo().getCompany_name());
				}

			}
			if (searchChannels) {
				log.debug("查询发布对象,先查询发布关系");
				ResultListVO<MServeObjectInfoVO> objResult = this.serveobjectinfoserviceimpl.queryByServiceId(vo_.getId());
				List<MServeObjectInfoVO> objList = objResult.getData();
				if (null != objList && !objList.isEmpty()) {
					log.debug("发布对象不为空开始查询发布对象");
					Long[] ids_ = new Long[objList.size()];
					int i = 0;
					StringBuilder business_ids_str = new StringBuilder();

					for (MServeObjectInfoVO objInfo : objList) {
						ids_[i] = objInfo.getCompany_id();
						i++;
						if (business_ids_str.length() > 0) {
							business_ids_str.append(",").append(objInfo.getCompany_id());
						} else {
							business_ids_str.append(objInfo.getCompany_id());
						}
					}
					vo_.setBusiness_ids_str(business_ids_str.toString());
					MCompanyForm form = new MCompanyForm();
					form.setIds_(ids_);
					ResultListVO<MCompanyVO> companyResult = this.mBaseCompanyServiceImpl.query_channel(form);
					List<MCompanyVO> companyList = companyResult.getData();
					vo_.setCompanyList(companyList);

				} else {
					log.debug("发布对象为空");
				}
			}
		}
	}

	/**12 获取数据集合 */
	public ResultDropDownListVO<MDropDownVO> queryListForDropDown( MGoodsInfoForm  form ){
		log.info("查询商品下拉列表form={}",form);
		ResultDropDownListVO<MDropDownVO> result = new ResultDropDownListVO<>();
		if(StringUtils.isBlank(form.getName())){
			result.setData(new ArrayList<>(0));
			log.info("name为空，直接返回");
			return result;
		}
		//发布的，（在售的）
		form.setState(MSystemConstants.ONLINE);
		
		 ResultListVO<MGoodsInfoVO> goodResult = this.goodsInfoServiceImpl.queryList(form);
		 List<MDropDownVO> dropList = new ArrayList<>(goodResult.getData().size());
		 for(MGoodsInfoVO goodsVO:goodResult.getData()) {
			 MDropDownVO dropVO = new MDropDownVO();
			 dropVO.setId(String.valueOf(goodsVO.getId()));
			 dropVO.setText(goodsVO.getName());
			 dropList.add(dropVO);
		 }
		 result.setData(dropList);
		 return result;
	}
}
